<?php

class JAuthentication
{
    /** @var Zend_Auth_Adapter_DbTable */
    protected $authAdapter;

    /** @var JAuthentication */
    protected static $instance;

    /**
     * @return JAuthentication
     */
    protected function __construct()
    {
        $this->authAdapter = new Zend_Auth_Adapter_DbTable(JDbAdapter::factory());
        $this->authAdapter->setTableName('USERS');
    }

    /**
     * @param string $identityColumn
     * @param string $credentialColumn
     */
    public function setRequiredInfo($identityColumn, $credentialColumn = '')
    {
        $this->authAdapter->setIdentityColumn($identityColumn);
        if (empty($credentialColumn)) {
            $this->authAdapter->setCredentialColumn($identityColumn);
        } else {
            $this->authAdapter->setCredentialColumn($credentialColumn);
        }
    }

    /**
     * @param string $identity
     * @param string $credential
     * @return Zend_Auth_Result
     */
    public function authenticate($identity, $credential = '')
    {
        $this->authAdapter->setIdentity($identity);
        if (empty($credential)) {
            $this->authAdapter->setCredential($identity);
        } else {
            $this->authAdapter->setCredential($credential);
        }

        $result =  $this->authAdapter->authenticate();
        $this->setRequiredInfo(null, null);

        return $result;
    }

    /**
     * @return JAuthentication
     */
    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new JAuthentication();
        }

        return self::$instance;
    }
}
